import { ref, type Ref } from 'vue'
import { debounce } from 'lodash-es'

type RefreshHandler = () => Promise<void>

export function usePullToRefresh(initialLoading: Ref<boolean> = ref(false)) {
  // 状态管理
  const isRefreshing = ref(false)
  const refreshError = ref<string | null>(null)
  const lastRefreshTime = ref<Date>(new Date())

  // 防抖处理（500ms内防止重复触发）
  const debouncedRefresh = debounce(async (refreshFn: RefreshHandler) => {
    try {
      isRefreshing.value = true
      refreshError.value = null

      await refreshFn()
      lastRefreshTime.value = new Date()

      // 成功提示保持1秒
      setTimeout(() => {
        isRefreshing.value = false
      }, 1000)
    } catch (error) {
      refreshError.value = error instanceof Error ? error.message : '刷新失败'
      isRefreshing.value = false
    } finally {
      initialLoading.value = false
    }
  }, 500)

  return {
    isRefreshing,
    refreshError,
    lastRefreshTime,
    handleRefresh: (refreshFn: RefreshHandler) => debouncedRefresh(refreshFn),
  }
}
